using WebApp8.Services;
using WebApp8.Models;
using WebApp8.Configuration;
using System.Text.Json.Serialization;
using System.Text.Json;

var builder = WebApplication.CreateBuilder(args);

// 添加Consul配置源
builder.Configuration.AddConsul(
    "http://localhost:8500",  // Consul服务器地址
    "WebApp8/config"         // 配置路径
);

// Add services to the container.
builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
        options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
        options.JsonSerializerOptions.Converters.Add(new DateOnlyJsonConverter());
    });

// 配置绑定
builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
var appSettings = builder.Configuration.GetSection("AppSettings").Get<AppSettings>();

// 注册数据库上下文
builder.Services.AddSingleton<DbContext>();

// 注册Consul服务
builder.Services.AddConsulConfig(builder.Configuration);

// 配置Kestrel服务器，使用配置文件中的端口
builder.WebHost.ConfigureKestrel(options =>
{
    options.ListenAnyIP(appSettings?.Port ?? 5000);
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

// 根据配置决定是否使用HTTPS重定向
if (appSettings?.UseHttps == true)
{
    app.UseHttpsRedirection();
}

app.UseAuthorization();

app.MapControllers();

// 注册服务到Consul
app.UseConsul(builder.Configuration);

app.Run();

public class DateOnlyJsonConverter : JsonConverter<DateOnly>
{
    private const string DateFormat = "yyyy-MM-dd";

    public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.String)
        {
            var dateStr = reader.GetString();
            if (DateOnly.TryParse(dateStr, out var date))
            {
                return date;
            }
        }
        return default;
    }

    public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString(DateFormat));
    }
}
